import axios from "axios";
import useUserStore from "@/store/user";
let userStoreCache: any = null;


const request = axios.create({
    baseURL: "http://192.168.1.7:8000/",
    timeout: 300000
});


// 请求拦截器
request.interceptors.request.use(config => {
    if (!userStoreCache) {
        userStoreCache = useUserStore();
    }
    const token = config.url?.includes('/refresh_token') ? userStoreCache.refresh_token : userStoreCache.access_token;
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
});

// 错误消息映射
const ERROR_MESSAGE_MAP: { [key: number]: string } = {
    200: '成功',
    201: '创建成功',
    202: '请求已接受，但未处理完成',
    204: '没有内容',
    301: '永久重定向',
    302: '临时重定向',
    303: '浏览器请求其他地址',
    304: '未修改',
    400: '签名无效',
    401: '未授权',
    403: '无效权限',
    404: '未找到',
    405: '方法不允许',
    406: '不接受',
    408: '请求超时',
    413: '请求实体过大',
    414: '请求URI过长',
    426: '需要升级',
    429: '请求过多',
    431: '请求头字段过大',
    500: '内部服务器错误',
    503: '服务不可用'

};

// 刷新令牌
async function refreshTokenAndRetry(error: any, retryCount = 0): Promise<any> {
    if (retryCount > 1) {
        return Promise.reject(new Error('Failed to refresh token'));
    }
    try {
        const res: any = await request.post('/refresh_token');
        if (res.code === 200) {
            userStoreCache.access_token = res.data.access_token;
            sessionStorage.setItem("access_token", res.data.access_token);
            return request(error.config);
        }
    } catch (refreshError) {
        return Promise.reject(new Error('retlogin'));
    }
}

// 响应拦截器
request.interceptors.response.use(res => {
    if (res.data.code == 200) {
        return res.data;
    }
    return Promise.reject(res.data.message);
}, async error => {
    const status = error.response.status;
    if (status === 401 && !error.config.url?.includes('/login') && !error.config.url?.includes('/refresh_token')) {
        return refreshTokenAndRetry(error, error.retryCount ? error.retryCount + 1 : 1);
    }
    const msg: string = ERROR_MESSAGE_MAP[status] || '网络错误';
    return Promise.reject({ status, msg });
});


export default request;